package com.emm.yixun.customer.service.impl;
import java.util.List;

import javax.jws.WebService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.TagService;
import com.emm.yixun.basic.service.TagValueService;
import com.emm.yixun.common.app.CustTagReqDto;
import com.emm.yixun.common.app.TagListResDto;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.model.Tag;
import com.emm.yixun.common.model.TagInfo;
import com.emm.yixun.common.model.TagValue;
import com.emm.yixun.common.model.dto.TagDto;
import com.emm.yixun.common.model.dto.TagValueDto;
import com.emm.yixun.common.model.enums.AnswerTypeEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.InputModeEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.customer.service.TagServiceFacade;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service("tagServiceFacade")
@WebService(name="com.emm.yixun.customer.service.TagServiceFacade")
public class TagServiceFacadeImpl implements TagServiceFacade{
	private  final Logger   logger = LoggerFactory.getLogger(this.getClass()); 
	
	@Autowired
	private TagService service;
	
	@Autowired
	private TagValueService tagValueService;

	@Override
	public Response<TagDto> save(TagDto dto) {
		Response<TagDto> response=new Response<TagDto>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			TagDto mDto=service.create(dto);
			if(null==mDto){
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(TagDto dto,Boolean selective) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==selective || null==dto || null==dto.getId()){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}
			
			if(selective){
				int count=service.update(dto);
				if(count>0){
					response.success(Integer.valueOf(count));
				}else{
					response.fail("90001", "更新数据失败");
				}
			}else{
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			TagDto mDto=new TagDto();
			mDto.setId(id);
			int count=service.destroy(mDto);
			if(count>0){
				response.success(Integer.valueOf(count));
			}else{
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}",e);
		}
		return response;
	}
	
    @Override
	public Response<Tag> findById(Long id) {
		Response<Tag> response=new Response<Tag>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			Tag entity=service.selectById(id);
			if(null==entity){
				response.fail("90001", "主键查询数据失败");
			}else{
				response.success(entity);;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public ResponseList<Tag> findByDto(TagDto dto) {
		ResponseList<Tag> response=new ResponseList<Tag>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<Tag> list=service.selectListByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Page<Tag> findPageByDto(TagDto dto, Integer begin,Integer row) {
		Page<Tag> response=new Page<Tag>();
		try {
			if(null==dto || null==begin || null==row){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<Tag> page = service.getPageModel(dto, begin, row);
			if(null==page.getRows()){
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response=page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}",e);
		}
		return response;
	}
	
	@Override
    public Page<TagInfo> getTagPage(TagDto dto, Integer begin,Integer row) {
        Page<TagInfo> response=new Page<TagInfo>();
        try {
            if(null==dto || null==begin || null==row){
                response.setSuccess(false);
                response.setErrorMsg("参数不合法");
                return response;
            }
            Page<TagInfo> page = service.getTagPage(dto, begin, row);
            if(null==page.getRows()){
                response.setSuccess(false);
                response.setErrorMsg("分页数据不存在");
                return response;
            }
            //格式化前台显示，题目加答案超过15字时进行截取
            List<TagInfo> list = page.getRows();
            for(TagInfo info : list) {
            	String tagName = info.getTagName();
            	if(StringUtils.isBlank(info.getAnswer())) {
            		continue;
            	}
            	String answer = info.getAnswer().replaceAll(",", "，");
            	String name = tagName + "：" + answer;
            	if(name.length() <= 15) {
            		continue;
            	}
            	answer = answer.substring(0, 15-tagName.length()) + "……";
            	info.setAnswer(answer);
            }
            response=page;
            response.setSuccess(true);
        } catch (Exception e) {
            response.setSuccess(false);
            response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
            logger.error("查询分页数据错误：{}",e);
        }
        return response;
    }
	
	@Override
    public ResponseList<TagInfo> getTagQuestionList(TagDto dto) {
        ResponseList<TagInfo> response=new ResponseList<TagInfo>();
        try {
            if(null==dto){
                response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
                return response;
            }
            List<TagInfo> list=service.getTagQuestionList(dto);
            if(null==list){
                response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
                return response;
            }
            for(TagInfo info : list){
                //将标签库的问题类型转换成本地环境类型
                if(InputModeEnum.INPUT.getNo().equals(info.getInputMode())){
                    info.setInputMode(AnswerTypeEnum.INPUT.getNo());
                }else if(InputModeEnum.CHECKBOX.getNo().equals(info.getInputMode())){
                    info.setInputMode(AnswerTypeEnum.CHECKBOX.getNo());
                }else if(InputModeEnum.RADIO.getNo().equals(info.getInputMode())){
                    info.setInputMode(AnswerTypeEnum.RADIO.getNo());
                }
                
                //答案为空时，重新开始循环
                if(StringUtils.isBlank(info.getAnswer())){
                    info.setAnswer("[]");
                    continue;
                }
                //格式化答案字段，["1","2","3"]
                String[] answer = info.getAnswer().split(",");
                JSONArray array = new JSONArray();
                for(int i = 0; i < answer.length; i++){
                    array.add(answer[i]);
                }
                info.setAnswer(array.toString());
            }
            response.success(list);
        } catch (Exception e) {
            response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
            logger.error("查询数据错误：{}",e);
        }
        return response;
    }

	@Override
    public ResponseList<TagInfo> getTagQuestionAnswerList(TagDto dto) {
        ResponseList<TagInfo> response=new ResponseList<TagInfo>();
        try {
            if(null==dto){
                response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
                return response;
            }
            List<TagInfo> list=service.getTagQuestionList(dto);
            if(null==list){
                response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
                return response;
            }
            for(TagInfo info : list){
                //将标签库的问题类型转换成本地环境类型
                if(InputModeEnum.INPUT.getNo().equals(info.getInputMode())){
                    info.setInputMode(AnswerTypeEnum.INPUT.getNo());
                }else if(InputModeEnum.CHECKBOX.getNo().equals(info.getInputMode())){
                    info.setInputMode(AnswerTypeEnum.CHECKBOX.getNo());
                }else if(InputModeEnum.RADIO.getNo().equals(info.getInputMode())){
                    info.setInputMode(AnswerTypeEnum.RADIO.getNo());
                }
                
                //获取答案选项
                JSONArray array = new JSONArray();
                //答案为空时，重新开始循环
                if(StringUtils.isBlank(info.getAnswer())){
                    info.setAnswer(array.toString());
                    continue;
                }
                TagValueDto valueDto = new TagValueDto();
                valueDto.setTagId(info.getTagId());
                valueDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
                List<TagValue> valueList = tagValueService.selectListByDto(valueDto);
                for(TagValue value : valueList ){
                    JSONObject json = new JSONObject();
                    json.put("id", value.getId());
                    json.put("answer", value.getTValue());
                    array.add(json);
                }
                info.setAnswer(array.toString());
            }
            response.success(list);
        } catch (Exception e) {
            response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
            logger.error("查询数据错误：{}",e);
        }
        return response;
    }
	
	/**
	 * 查询标签分类
	 */
	@Override
    public TagListResDto getTagList(CustTagReqDto dto){
		TagListResDto tagDto = new TagListResDto();
		TagDto entity = new TagDto();
		entity.setParentId(0L);
		List<Tag> list = service.selectListByDto(entity);
		if(list == null) {
			tagDto.setResult(ResultEnum.FAILURE.getNo());
			return tagDto;
		}
		for(Tag tag : list) {
			tag.setTagId(tag.getId());
		}
		tagDto.setTagList(list);
		tagDto.setResult(ResultEnum.SUCCESS.getNo());
		return tagDto;
	}
}
